<?php
namespace control;
/*
*业绩目标类
*/

class performanceTargetClass extends adIndexClass
{
    private const page = 'performanceTarget';
    private const table = 'performance_target';
    private const title = '业绩目标';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'month'          => [
                        'name'  => L('performanceTarget.home.month'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'staffName' => [
                        'name'  => L('performanceTarget.home.staff'),
                        'width' => 200,
                    ],
                    'money'  => [
                        'name'  => L('performanceTarget.home.KPI')."(" . static::$unit . ")",
                        'width' => 200,
                    ],
                    'text'         => [
                        'name'  => L('performanceTarget.home.text'),
                        'width' => 400,
                    ],
                    'stid'          => [
                        'name'  => L('performanceTarget.home.stid'),
                        'width' => 200,
                    ],
                    'time'          => [
                        'name'  => L('performanceTarget.home.time'),
                        'width' => 300,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('performanceTarget.home.staff') => text(array("name" => "name")),
                    L('performanceTarget.home.month')   => text(array("name" => "month", 'laydate' => ['type' => 'month'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{id:'" . suiji() . "'})\" class='spanButton'>".L('performanceTarget.home.new')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('" . $this->get('cla') . "', 'operate', {'act': 'del'})\">".L('performanceTarget.home.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "staffName" => $this->post('name'),//名称
        );
        //全等查询数组
        $equal = array(
            "month" => $this->post('month'),//负责人
            'coid'=>self::$coid
        );
        $and = "";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('performanceTarget.home.detail'), "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('performanceTarget.home.month')."：" => text(["name" => "month", 'laydate' => ['type' => 'month'], "value" => $info['month']]),
                    must . L('performanceTarget.home.staff')."：" => selectMultiple(["name" => "staffId[]", 'multiple' => true, 'title' => L('performanceTarget.home.staff'), 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['staffId']]),
                ],
                [
                    must . L('performanceTarget.home.KPI')."：" => text(["name" => "money", 'type'=>'number','class' => 'text', 'unit' =>  static::$unit , "value" => $info['money']]),
                ],
                [
                    L('performanceTarget.home.text')."：" => textarea(["name" => "text", 'class' => 'textarea', "value" => $info['text']]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('performanceTarget.home.edit'), "height" => 300, "width" => 900, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $staffId = $this->post('staffId')?:[];
        $field = [
            'month' => $this->post('month'),
            'money' => $this->post('money'),
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'month' => L('performanceTarget.home.month'),
            'money' => L('performanceTarget.home.KPI'),
        ];
        $rules = [
            'month' => 'required',
            'money' => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        $warn = '';
        $staffName = '';
        if (is_array($staffId)) {
            foreach ($staffId as $stid) {
                $staff = query('staff', "stid = '$stid'");
                if (static::total(array('table' => self::table, 'where' => "staffId like '%$stid%' and month = '$field[month]' and id !='$id'")) > 0) {
                    $warn = str_replace(['{{staffName}}'], [$staff['name']], L('performanceTarget.editEdit.already'));
                    break;
                }
                $staffName .= $staff['name'] . ',';
            }
        }

        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('performanceTarget.editEdit.power');
        } elseif (empty($staffId) || !is_array($staffId)) {
            $json['warn'] = L('performanceTarget.editEdit.choiceStaff');
        } elseif (!empty($warn)) {
            $json['warn'] = $warn;
        } else {
            $where = " id = '$id'";
            $info = query(self::table, $where);
            $field['staffId'] = implode(',',$staffId);
            $field['staffName'] = $staffName;
            if (!$info['id']) {
                $array = array_merge($field, [
                    'id' => self::getId(),
                    'coid'=>self::$coid,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $array]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('performanceTarget.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }

        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('performanceTarget.operate.del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('performanceTarget.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('performanceTarget.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('performanceTarget.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = L('performanceTarget.delete.success');
                $x++;
                $text .= str_replace(['{{id}}'], [$info['id']], L('performanceTarget.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text =str_replace(['{{staffName}}'], [$this->control['name']], L('performanceTarget.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('performanceTarget.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
